package bin_tree;

public class MyBinaryTree {
    //孩子双亲表示法
    private static class Node {
        private char val;
        private Node left;
        private Node right;
        public Node(char val) {
            this.val = val;
        }
    }

    //生成一个测试二叉树
    public Node buildATree() {
        Node nodeA = new Node('A');
        Node nodeB = new Node('B');
        Node nodeC = new Node('C');
        Node nodeD = new Node('D');
        Node nodeE = new Node('E');
        Node nodeF = new Node('F');
        Node nodeG = new Node('G');
        Node nodeH = new Node('H');
        nodeA.left = nodeB;
        nodeA.right = nodeC;
        nodeB.left = nodeD;
        nodeB.right = nodeE;
        nodeE.left = nodeG;
        nodeG.right = nodeH;
        nodeC.right = nodeF;
        return nodeA;
    }
    //先序遍历
    //根左右
    //传入一个二叉树的根节点，根据先序遍历访问该二叉树
    public void preOrder(Node root){
        if(root == null){
            return;
        }
        //根
        System.out.print(root.val + " ");
        //左树
        preOrder(root.left);
        //右树
        preOrder(root.right);
    }

    /**
     * 传入一个二叉树的根节点root，根据中序遍历访问该二叉树
     * 左根右
     */
     //
    public void inOrder(Node root) {
        if (root == null) {
            return;
        }
        //先按照中序遍历访问左子树
        inOrder(root.left);
        System.out.print(root.val + " ");
        //按照中序再访问右子树
        inOrder(root.right);
    }
        /**
         * 传入一个二叉树根节点root,根据后序遍历访问该二叉树
         * 左右根
         */
    public void postOrder(Node root){
        if(root == null){
            return;
        }
        //左
         postOrder(root.left);
        //右
        postOrder(root.right);
        //根
            System.out.print(root.val + " ");
        }


    public static void main(String[] args) {
        MyBinaryTree myBinaryTree = new MyBinaryTree();
        Node root = myBinaryTree.buildATree();
        System.out.println("先序遍历结果:");
        myBinaryTree.preOrder(root);
        System.out.println();
        System.out.println("---------------------");
        System.out.println("中序遍历结果:");
        myBinaryTree.inOrder(root);
        System.out.println();
        System.out.println("---------------------");
        System.out.println("后序遍历结果:");
        myBinaryTree.postOrder(root);

    }

}

